package com.plian.system.service.im.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.bean.im.FundProjectExcelBean;
import com.plian.system.cache.UserCache;
import com.plian.system.common.status.CheckStatus;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dto.im.FundProjectInfoDTO;
import com.plian.system.entity.im.*;
import com.plian.system.entity.sys.ApprovalMessage;
import com.plian.system.mapper.im.FundProjectExecutionMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.im.*;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.im.FundInvestedProjectVO;
import com.plian.system.vo.im.FundProjectExecutionVO;
import com.plian.system.vo.im.FundProjectInfoVO;
import com.plian.system.vo.im.FundProjectVO;
import com.plian.system.vo.yth.YthResult;
import com.plian.system.wrapper.im.FundInvestedProjectWrapper;
import com.plian.system.wrapper.im.FundProjectAmountDetailWrapper;
import com.plian.system.wrapper.im.FundProjectExecutionWrapper;
import com.plian.system.wrapper.im.FundProjectWrapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.FUND_EXECUTION;
import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.KT_TYPE;
import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 基金项目投资计划执行
 服务实现类
 *
 * @author BladeX
 * @since 2022-04-15
 */
@Service
@AllArgsConstructor
public class FundProjectExecutionServiceImpl extends BaseServiceImpl<FundProjectExecutionMapper, FundProjectExecution> implements IFundProjectExecutionService, BaseFlowService {

	private IFundProjectService fundProjectService;

	private FormWorkflowService formWorkflowService;

	private FundProjectExecutionWrapper fundProjectExecutionWrapper;

	private IFormCodeService formCodeService;

	private FundProjectWrapper fundProjectWrapper;

	private IFundInvestedProjectService fundInvestedProjectService;

	private FundInvestedProjectWrapper fundInvestedProjectWrapper;

	private IFundProjectInfoService fundProjectInfoService;

	private FundProjectAmountDetailWrapper fundProjectAmountDetailWrapper;

	private IApprovalMessageService approvalMessageService;

	private IFundProjectAmountDetailService fundProjectAmountDetailService;

	private IOrgService orgService;
	@Override
	public boolean saveOrUpdate(FundProjectExecution fundProjectExecution) {
		if (!Optional.ofNullable(fundProjectExecution.getStatus()).isPresent()) {
			fundProjectExecution.setStatus(FormStatusConstant.UNREVIEWED);
		}
		if (!Optional.ofNullable(fundProjectExecution.getId()).isPresent()) {
			fundProjectExecution.setCode(formCodeService.getCode(FormTypeConstant.IM_FUNDPROJECT_EXECUTION));
			fundProjectExecution.setFormType(String.valueOf(FormTypeConstant.IM_FUNDPROJECT_EXECUTION));
		}
		return super.saveOrUpdate(fundProjectExecution);
	}

	@Override
	public IPage<FundProjectExecutionVO> selectFundProjectExecutionPage(IPage<FundProjectExecutionVO> page, FundProjectExecutionVO fundProjectExecution) {
		return page.setRecords(baseMapper.selectFundProjectExecutionPage(page, fundProjectExecution));
	}
	@Override
	public String checkMonth(FundProjectExecution fundProjectExecution) {
		LambdaQueryWrapper<FundProjectExecution> queryWrapper = new LambdaQueryWrapper<>();
		if (!Optional.ofNullable(fundProjectExecution.getFilingMonth()).isPresent()) {
			return "填报时间为空";
		}
		if (!Optional.ofNullable(fundProjectExecution.getFilingUnitId()).isPresent()){
			return "填报单位为空";
		}
		queryWrapper.eq(FundProjectExecution::getFilingUnitId,fundProjectExecution.getFilingUnitId());
		queryWrapper.eq(FundProjectExecution::getFilingMonth, fundProjectExecution.getFilingMonth());
		FundProjectExecution one = getOne(queryWrapper);
		if (!Optional.ofNullable(one).isPresent()){
			return null;
		}
		if (one.getId().equals(fundProjectExecution.getId())){
			return null;
		}
		return "该月份已填报";
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean submit(FundProjectExecution fundProjectExecution) {
		boolean result=saveOrUpdate(fundProjectExecution);
		if(result){
			List<FundProject> fundProjects = fundProjectExecution.getFundProjects();
			if (CollectionUtil.isNotEmpty(fundProjects)){
				for (FundProject fundProject : fundProjects){
					if (fundProject.getId() != null &&
							Optional.ofNullable(fundProject.getIsDeleted()).isPresent() && fundProject.getIsDeleted().intValue() == 1) {
						fundProjectAmountDetailService.removeByBaseId(fundProject.getId());
						fundProjectService.removeById(fundProject.getId());
					}else {
						fundProject.setFundProjectExecutionId(fundProjectExecution.getId());
						fundProjectService.submit(fundProject);
					}
				}
			}
		}
		return result;
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean deleteLogic(List<Long> ids) {
		for (Long id : ids) {
			FundProjectExecution fundProjectExecution = getById(id);
			if (fundProjectExecution == null) {
				return false;
			} else if (fundProjectExecution.getStatus() != null &&
					(fundProjectExecution.getStatus() != FormStatusConstant.STASH && fundProjectExecution.getStatus() != FormStatusConstant.UNREVIEWED)) {
				return false;
			}
			formWorkflowService.deleteProcessInstance(String.valueOf(id));
		}
		boolean result = super.deleteLogic(ids);
		return result;
	}

	@Override
	public HashMap<String,Object> commit(String id) {
		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW, null);

		//将需要提交的流程变量返回，用于工作流侧
		return new HashMap<String,Object>();
	}

	@Override
	public Boolean finish(String id) {
		/**
		 * 设置审批人和审批时间
		 */
		FundProjectExecution fundProjectExecution = getById(id);
		fundProjectExecution.setApprovedUser(TokenUtil.getTokenUserId());
		Date now = DateUtil.now();
		fundProjectExecution.setApprovedTime(now);
		updateById(fundProjectExecution);

		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH, "审批通过");
	}

	@Override
	public Boolean reject(String id, int formState, String comment) {
		return handleStatus(Long.valueOf(id), formState, comment);
	}

	@Override
	public List<PageData> findByIds(List<String> formIds) {
		List<FundProjectExecution> fundProjectExecutions = list(new LambdaQueryWrapper<FundProjectExecution>().in(FundProjectExecution::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA))));
		List<FundProjectExecutionVO> fundProjectExecutionVOS = fundProjectExecutionWrapper.entityToVO(fundProjectExecutions);
		List<PageData> pageDataList = new ArrayList<>();
		try{
			if (CollectionUtil.isNotEmpty(fundProjectExecutionVOS)){
				for (FundProjectExecutionVO vo : fundProjectExecutionVOS){
					PageData pd = new PageData();
					pd.put("id", vo.getId());
					pd.put("UNITNAME", vo.getFilingUnitName());
					pd.put("APPLICANTNAME", vo.getCreateUserName());
					pd.put("applicantId", vo.getCreateUser());
					pd.put("applyOrganizationId", vo.getFilingUnitId());
					pd.put("formType", FormTypeConstant.IM_FUNDPROJECT_EXECUTION);
					pd.put("orgName", vo.getFilingUnitName());
					pageDataList.add(pd);
				}
			}

			return pageDataList;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
		return pageDataList;
	}

	@Override
	public List<Integer> getFormType() {
		return Collections.singletonList(FormTypeConstant.IM_FUNDPROJECT_EXECUTION);
	}

	@Override
	public R<FundProjectExecutionVO> getDetailObj(FundProjectExecutionVO fundProjectExecutionVO) {
		if(!Optional.ofNullable(fundProjectExecutionVO).isPresent()){
			return new R(CommonCode.FAIL);
		}
		List<FundProjectVO> fundProjectVOS = fundProjectWrapper.entityToVO(fundProjectService.list(new LambdaQueryWrapper<FundProject>()
				.eq(FundProject::getFundProjectExecutionId, fundProjectExecutionVO.getId())));
		fundProjectExecutionVO.setFundProjectVOS(fundProjectService.getDetailPd(fundProjectVOS));
		return R.data(fundProjectExecutionVO);
	}

//	@Override TODO DEL
//	public void updateProject(FundProjectExecution fundProjectExecution){
//		//获取执行基金项目情况
//		List<FundProject> fundProjects = fundProjectService.list(new LambdaQueryWrapper<FundProject>().eq(FundProject::getFundProjectExecutionId, fundProjectExecution.getId()));
//		if (CollectionUtil.isNotEmpty(fundProjects)){
//			//获取基金项目情况
//			List<Long> infoIds = fundProjects.stream().map(FundProject::getFundProjectInfoId).filter(m -> Optional.ofNullable(m).isPresent()).collect(Collectors.toList());
//			List<FundProjectInfo> fundProjectInfos = fundProjectInfoService.listByIds(infoIds);
//			if (CollectionUtil.isNotEmpty(fundProjectInfos)){
//				for (FundProject fundProject:fundProjects){
//					//筛选
//					List<FundProjectInfo> fundProjectInfoList = fundProjectInfos.stream().filter(m -> fundProject.getFundProjectInfoId().equals(m.getId())).collect(Collectors.toList());
//					if (CollectionUtil.isNotEmpty(fundProjectInfoList)){
//						FundProjectInfo fundProjectInfo = fundProjectInfoList.get(0);
//						projectInfoCopyProject(fundProject,fundProjectInfo);
//					}
//
//				}
//				fundProjectService.saveList(fundProjects);
//			}
//		}
//
//	}

	/**
	 * @Author: Take-off
	 * @Description: //TODO 基金信息更新
	 * @Date: 9:53 AM 2023/2/8
	 * @Param: [fundProject, fundProjectInfo]
	 * @return: void
	 **/
	private void projectInfoCopyProject(FundProject fundProject,FundProjectInfo fundProjectInfo){
		fundProject.setCompanyId(fundProjectInfo.getCompanyId());
		fundProject.setFundName(fundProjectInfo.getFundName());
		fundProject.setInvestmentSubject(fundProjectInfo.getInvestmentSubject());
		fundProject.setFundCategory(fundProjectInfo.getFundCategory());
		fundProject.setStartTime(fundProjectInfo.getStartTime());
		fundProject.setEndTime(fundProjectInfo.getEndTime());
		fundProject.setGp(fundProjectInfo.getGp());
		fundProject.setLp(fundProjectInfo.getLp());
		fundProject.setFundScale(fundProjectInfo.getFundScale());
		fundProject.setContributedCapital(fundProjectInfo.getContributedCapital());
		fundProject.setCompanyContributedCapital(fundProjectInfo.getCompanyContributedCapital());
		fundProject.setHasContributedCapital(fundProjectInfo.getHasContributedCapital());
		fundProject.setGpDetail(fundProjectInfo.getGpDetail());
		fundProject.setLpDetail(fundProjectInfo.getLpDetail());
		fundProject.setOrderNumber(fundProjectInfo.getOrderNumber());
		fundProject.setManageMode(fundProjectInfo.getManageMode());
		fundProject.setFundType(fundProjectInfo.getFundType());
		fundProject.setOrganizationForm(fundProjectInfo.getOrganizationForm());
		fundProject.setFundStatus(fundProjectInfo.getFundStatus());
		fundProject.setInternalYieldRate(fundProjectInfo.getInternalYieldRate());
		fundProject.setManagerType(fundProjectInfo.getManagerType());
		fundProject.setProjectSituation(fundProjectInfo.getProjectSituation());
		fundProject.setSubscribedCapital(fundProjectInfo.getSubscribedCapital());
		fundProject.setYearContributedCapital(fundProjectInfo.getYearContributedCapital());
		fundProject.setCompanyYearContributedCapital(fundProjectInfo.getCompanyYearContributedCapital());
		fundProject.setAffiliatedOrgFullName(fundProjectInfo.getAffiliatedOrgFullName());
		fundProject.setFundNature(fundProjectInfo.getFundNature());
	}

	@Override
	public List<FundProjectVO> executionListDetail(List<FundProjectExecutionVO> fundProjectExecutionVOS, FundProjectInfoDTO fundProjectInfoDTO) {
		for(FundProjectExecutionVO fundProjectExecutionVO:fundProjectExecutionVOS){
			getDetailObj(fundProjectExecutionVO);
		}
		List<FundProjectVO> list=new ArrayList<>();
		Boolean natureFlag=Optional.ofNullable(fundProjectInfoDTO.getFundNatures()).isPresent()&&fundProjectInfoDTO.getFundNatures().size()>0;
		for(FundProjectExecutionVO f:fundProjectExecutionVOS){
			List<FundProjectVO> voList=f.getFundProjectVOS();
			if(natureFlag){
				//按照基金性质进行过滤
				voList=voList.stream().filter(record->fundProjectInfoDTO.getFundNatures().contains(record.getFundNature())).collect(Collectors.toList());
			}
			list.addAll(voList);
		}
		FundProjectVO total=new FundProjectVO();
		total.setAffiliatedOrgFullName("合计");
		BigDecimal investmentAll=new BigDecimal(0);
		for(FundProjectVO fundProjectVO:list){
			total.setGp(BigDecimalUtil.add(total.getGp(), fundProjectVO.getGp()));
			total.setLp(BigDecimalUtil.add(total.getLp(), fundProjectVO.getLp()));
			total.setFundScale(BigDecimalUtil.add(total.getFundScale(), fundProjectVO.getFundScale()));
			total.setSubscribedCapital(BigDecimalUtil.add(total.getSubscribedCapital(), fundProjectVO.getSubscribedCapital()));
			total.setCompanyContributedCapital(BigDecimalUtil.add(total.getCompanyContributedCapital(), fundProjectVO.getCompanyContributedCapital()));
			total.setContributedCapital(BigDecimalUtil.add(total.getContributedCapital(), fundProjectVO.getContributedCapital()));
			total.setYearContributedCapital(BigDecimalUtil.add(total.getYearContributedCapital(), fundProjectVO.getYearContributedCapital()));
			total.setHasContributedCapital(BigDecimalUtil.add(total.getHasContributedCapital(), fundProjectVO.getHasContributedCapital()));
			total.setCompanyYearContributedCapital(BigDecimalUtil.add(total.getCompanyYearContributedCapital(), fundProjectVO.getCompanyYearContributedCapital()));
			total.setInternalYieldRate(BigDecimalUtil.add(total.getInternalYieldRate(), fundProjectVO.getInternalYieldRate()));
			List<FundInvestedProjectVO> fundInvestedProjectVOS=fundProjectVO.getFundInvestedProjectVOS();
			BigDecimal investment=fundInvestedProjectVOS.stream().map(record->record.getInvestment()==null?new BigDecimal(0):record.getInvestment()).reduce(BigDecimal.ZERO,BigDecimal::add);
			investmentAll=BigDecimalUtil.add(investment, investmentAll);
			total.setInvestment(investmentAll);
		}
		List<FundInvestedProjectVO> finalFundInvestedProjectVO=new ArrayList<>();
		FundInvestedProjectVO last=new FundInvestedProjectVO();
		last.setInvestment(investmentAll);
		finalFundInvestedProjectVO.add(last);
		total.setFundInvestedProjectVOS(finalFundInvestedProjectVO);
		if(list.size()>0){
			list.add(total);
		}
		return list;
	}

	@Override
	public List<FundProjectVO> getFundProjectListByOrgAndMonth(String month, String fillingUnitId) {
		List<FundProjectVO> result=new ArrayList<>();
		FundProjectExecution fundProjectExecution=getOne(new LambdaQueryWrapper<FundProjectExecution>()
		.eq(FundProjectExecution::getFilingMonth,month).eq(FundProjectExecution::getFilingUnitId,fillingUnitId));
		if(fundProjectExecution!=null){
			List<FundProjectVO> fundProjectVOS = fundProjectWrapper.entityToVO(fundProjectService.list(new LambdaQueryWrapper<FundProject>()
					.eq(FundProject::getFundProjectExecutionId, fundProjectExecution.getId())));
			List<FundProjectInfoVO> fundProjectInfoList = fundProjectInfoService.detailList(fundProjectInfoService.list());
			Map<Long,FundProjectInfoVO> fundProjectInfoMap=fundProjectInfoList.stream().collect(Collectors.toMap(record->record.getId(),record->record));
			for(FundProjectVO vo:fundProjectVOS){
				Long baseId=vo.getId();
				Long infoId=vo.getFundProjectInfoId();
				FundProjectVO temp=new FundProjectVO();
				temp=vo;
				temp.setId(baseId);
				if(fundProjectInfoMap.containsKey(infoId)){
					FundProjectInfoVO f=fundProjectInfoMap.get(infoId);
					temp=fundProjectWrapper.infoToEntity(f);
					temp.setFundProjectInfoId(infoId);
				}
				temp.setFundInvestedProjectVOS(fundInvestedProjectWrapper
						.entityToVO(fundInvestedProjectService.list(new LambdaQueryWrapper<FundInvestedProject>()
								.eq(FundInvestedProject::getFundProjectId, baseId))));
				result.add(temp);
			}
			//对id去空，防止保存的时候
			for(FundProjectVO fundProjectVO:result){
				fundProjectVO.setId(null);
				fundProjectVO.setBaseInvestmentExecutionId(null);
				fundProjectVO.setCreateUser(null);
				fundProjectVO.setCreateTime(null);
				fundProjectVO.setUpdateUser(null);
				fundProjectVO.setUpdateTime(null);
				List<FundInvestedProjectVO> fundInvestedProjects=fundProjectVO.getFundInvestedProjectVOS();
				for(FundInvestedProjectVO fundInvestedProjectVO:fundInvestedProjects){
					fundInvestedProjectVO.setId(null);
					fundInvestedProjectVO.setFundProjectId(null);
					fundInvestedProjectVO.setCreateUser(null);
					fundInvestedProjectVO.setCreateTime(null);
					fundInvestedProjectVO.setUpdateUser(null);
					fundInvestedProjectVO.setUpdateTime(null);
				}
			}
		}
		return result;
	}

	@Override
	public void refreshDetailData() {
		List<FundProjectInfo> fundProjectInfos = fundProjectInfoService.list();
		List<FundProject> fundProjects = fundProjectService.list();
		List<FundProjectAmountDetail> fundProjectAmountDetailList = fundProjectAmountDetailService.list();
		Map<Long, List<FundProjectAmountDetail>> projectIdMap = fundProjectAmountDetailList.stream()
				.collect(Collectors.groupingBy(FundProjectAmountDetail::getFundProjectId));
		List<FundProjectAmountDetail> insertList = new ArrayList<>();
		int countA = 0;
		int countB = 0;
		for (FundProject fundProject : fundProjects){
			if (projectIdMap.containsKey(fundProject.getId())){
				countA++;
				continue;
			}
			if (!projectIdMap.containsKey(fundProject.getFundProjectInfoId())){
				countB++;
				continue;
			}
			List<FundProjectAmountDetail> fundProjectAmountDetails = projectIdMap.get(fundProject.getFundProjectInfoId());
			for (FundProjectAmountDetail oldDetail : fundProjectAmountDetails){
				FundProjectAmountDetail newDetail = fundProjectAmountDetailWrapper.copyEntity(oldDetail);
				newDetail.setId(null);
				newDetail.setFundProjectId(fundProject.getId());
				insertList.add(newDetail);
			}
		}
		if (CollectionUtil.isNotEmpty(insertList)){
			fundProjectAmountDetailService.saveBatch(insertList);
		}
	}

	@Override
	public String saveFundProjectExecution(String data) {
		YthResult ythResult = new YthResult();
		//成功的id集合
		List<String> successIds = new ArrayList<>();
		//失败的id集合
		List<String> failIds = new ArrayList<>();
		//失败的原因
		List<String> failReasons = new ArrayList<>();
		//将json字符串转换成list
		List<FundProjectExecution> dataList = JSON.parseArray(data, FundProjectExecution.class);
		if (CollectionUtil.isNotEmpty(dataList)){
			Map<String, String> orgSourceMap = orgService.getSourceId();
			//根据datasourceIds 查询出所有的数据
			List<FundProjectExecution> list = list(new LambdaQueryWrapper<FundProjectExecution>().in(FundProjectExecution::getDataSourceId, dataList.stream().map(FundProjectExecution::getDataSourceId).toArray()));
			if (CollectionUtil.isNotEmpty(list)){
				//删除子集
				List<Long> ids = list.stream().map(FundProjectExecution::getId).collect(Collectors.toList());
				List<FundProject> fundProjects = fundProjectService.list(new LambdaQueryWrapper<FundProject>().in(FundProject::getFundProjectExecutionId, ids));
				if (CollectionUtil.isNotEmpty(fundProjects)){
					List<Long> fundProjectIds = fundProjects.stream().map(FundProject::getId).collect(Collectors.toList());
					fundProjectService.removeByIds(fundProjectIds);
					fundInvestedProjectService.remove(new LambdaQueryWrapper<FundInvestedProject>().in(FundInvestedProject::getFundProjectId, fundProjectIds));
				}
			}
			//如果数据库中有数据，就更新，没有就新增
			for (FundProjectExecution entity:dataList){
				transfer(entity,orgSourceMap);
				//id重复略过
				if (CollectionUtil.isNotEmpty(list)){
					List<String> olIds = list.stream().map(FundProjectExecution::getDataSourceId).collect(Collectors.toList());
					String dataSourceId = entity.getDataSourceId();
					//判断数据库中是否有数据
					if (olIds.contains(dataSourceId)){
						for (FundProjectExecution oldEntity:list){
							if (dataSourceId.equals(oldEntity.getDataSourceId())){
								//判断status是否为0，如果是0，就更新，不是0，就不更新
								if (CheckStatus.checkCode(oldEntity.getStatus())){
									successIds.add(dataSourceId);
									entity.setId(oldEntity.getId());
									entity.setDataSource(YthConstant.DATA_NINGBO);
									submit(entity);
									list.remove(oldEntity);
									break;
								}else {
									failIds.add(dataSourceId);
									failReasons.add("dataSourceId:"+dataSourceId+"数据已提交且已经在流程中，无法更新");
									break;
								}
							}
						}
					}else {
						//如果数据库中没有数据，就新增
						entity.setDataSource(YthConstant.DATA_NINGBO);
						submit(entity);
						successIds.add(entity.getDataSourceId());
					}
				}else {
					//如果数据库中没有数据，就新增
					entity.setDataSource(YthConstant.DATA_NINGBO);
					submit(entity);
					successIds.add(entity.getDataSourceId());
				}
			}
		} else {
			failReasons.add("数据为空");
		}
		ythResult.setSuccessIds(successIds);
		ythResult.setFailIds(failIds);
		ythResult.setFailReason(StringUtils.join(failReasons, ";"));
		//ythResult转换成json字符串
		return JSON.toJSONString(ythResult);
	}

	private void transfer(FundProjectExecution entity, Map<String, String> orgSourceMap){
		Optional.ofNullable(entity.getFilingUnitId()).ifPresent(m ->
				{
					String orgId = orgSourceMap.get(m);
					if (StringUtil.isNotBlank(orgId)){
						entity.setFilingUnitId(orgId);
						entity.setCreateCompanyId(orgId);
					}
				}
		);

	}


	public List<FundProjectExcelBean> excelValueSet(List<FundProjectExecutionVO> fundProjectExecutionVOS){
		List<FundProjectExcelBean> fundProjectExcelBeans=new ArrayList<>();
		FundProjectExcelBean total = FundProjectExcelBean.builder().build();
		if(CollectionUtil.isNotEmpty(fundProjectExecutionVOS)){
			int index=0;
			for(int i=0;i< fundProjectExecutionVOS.size();i++){
				FundProjectExcelBean fundProjectExcelBean=new FundProjectExcelBean();
				BeanUtils.copyProperties(fundProjectExecutionVOS.get(i),fundProjectExcelBean);
				fundProjectExcelBean.setIndex(String.valueOf(i + 1));

			}
		}
		return fundProjectExcelBeans;
	}

	@Override
	public void goBackToStash(String formId) {
		handleStatus(Long.valueOf(formId), UNREVIEWED, null);
	}

	/**
	 * 统一处理状态机事件方法
	 * @param id 主键
	 * @param updateStatus 更新状态
	 * @param comment
	 * @return boolean
	 */
	private Boolean handleStatus(Long id, int updateStatus, String comment) {
		try {
			FundProjectExecution fundProjectExecution = getById(id);
			fundProjectExecution.setStatus(updateStatus);
			if (StringUtil.isNotBlank(fundProjectExecution.getDataSource()) &&
					StringUtil.isNotBlank(fundProjectExecution.getDataSourceId())){
				if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT){
					ApprovalMessage approvalMessage = new ApprovalMessage();
					approvalMessage.setDataSourceId(fundProjectExecution.getDataSourceId());
					approvalMessage.setType(FUND_EXECUTION);
					approvalMessage.setOpinion(comment);
					approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
					approvalMessage.setIsSend(1);
					approvalMessage.setDataSourceType(KT_TYPE);
					approvalMessage.setFilingCode(fundProjectExecution.getCode());
					if (fundProjectExecution.getDataSource().equals(YthConstant.DATA_NINGBO)) {
						approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
						approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
						approvalMessage.setFormType(FormTypeConstant.IM_FUNDPROJECT_EXECUTION);
					}
					approvalMessageService.save(approvalMessage);
				}
			}
			updateById(fundProjectExecution);
			return true;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return false;
		}
	}
}
